package com.pogodin.wave;

public class IntAdding {

    public static void main(String [] args){
        System.out.println(add(5, -7));
        System.out.println(recursiveAdd(5, -7));
        System.out.println(isSameSign(5, -7));
        System.out.println(isSameSign(5, 7));
        System.out.println(isSameSign(-5, -7));

    }

    public static int add(int x, int y) {

        int xor, and, temp;
        System.out.println(Integer.toBinaryString(x));
        System.out.println(Integer.toBinaryString(y));
        and = x & y; /* Obtain the carry bits */
        xor = x ^ y; /* resulting bits */

        System.out.println(Integer.toBinaryString(and));
        System.out.println(Integer.toBinaryString(xor));


        while(and != 0 ) /* stop when carry bits are gone */
        {
            and <<= 1; /* shifting the carry bits one space */
            System.out.println("and <<= 1 :::" + Integer.toBinaryString(and));
            temp = xor ^ and; /* hold the new xor result bits*/
            System.out.println("temp = xor ^ and; :::" + Integer.toBinaryString(temp));
            and &= xor; /* clear the previous carry bits and assign the new carry bits */
            System.out.println("and &= xor; :::" + Integer.toBinaryString(and));
            xor = temp; /* resulting bits */
        }
        return xor; /* final result */
    }

    public static int recursiveAdd(int a, int b){
        if(b == 0)return a;
        int sum = a ^ b;
        int carry = (a & b) << 1;
        return recursiveAdd(sum, carry);
    }

    public static boolean isSameSign(int a, int b){
        return (a^b)>0;
    }

}
